package com.auto.survey.activity.geosurv.backward

import android.util.Log
import android.view.View
import android.widget.TextView
import com.auto.survey.R
import com.auto.survey.activity.geosurv.backward.entity.Observation
import com.auto.survey.activity.geosurv.backward.entity.Point
import com.auto.survey.activity.geosurv.backward.jni.MyNativeClass
import com.auto.survey.base.BaseActivity
import com.auto.survey.util.Helper

class BackWardActivity : BaseActivity() {
    override fun initView() {
        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.action_bar)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.action_bar)
        mComment_title?.setTitle("后方交会")

//        val points = listOf(
//            Point(1393.1563,860.5537, 12.8889),
//            Point(1393.0241,860.7879, 12.8904),
//            Point(1392.8942, 861.0615, 12.9506))
//
//        val observations = listOf(Observation(1, 0.0, 2.9481, 0.0),
//            Observation(2, 0.535762202591946, 2.9661, 0.5236),
//            Observation(3, 0.626629628753367, 2.9659, 1.0472))

        val points = listOf(
            Point(1000.0, 1000.0, 0.0),
            Point(2000.0, 1200.0, 0.0),
            Point(1500.0, 2000.0, 0.0))

        val observations = listOf(Observation(1, 0.0, 0.0, 0.0),
            Observation(2, 0.5236, 0.0, 0.5236),
            Observation(3, 1.047, 0.0, 1.0472))




        val tv = findViewById<TextView>(R.id.tv_jni)
        val result = MyNativeClass().calculateResectionToJNI(points, observations,3)

        val strSucc = "是否成功：${result.success}"
        val strXerr = "X方向误差 = ${Helper.formateDecimal(result.errorX)}"
        val strYerr = "Y方向误差= ${Helper.formateDecimal(result.errorY)}"
        val strRms = "点位中误差 = ${Helper.formateDecimal(result.errorRMS)}"
        val strX = "测站X坐标 = ${Helper.formateDecimal(result.station.x)}"
        val strY = "测站Y坐标 =${Helper.formateDecimal(result.station.y)}"
        val strZ = "测站z坐标 =${Helper.formateDecimal(result.station.z)}"

        val content = strSucc + "\n" + strXerr + "\n" + strYerr + "\n" + strRms + "\n" + strX + "\n" + strY + "\n" + strZ

        tv.text = content
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_back_ward
    }

    // 在合适的位置（如Activity初始化时）添加
    // 你的反射函数
    private fun printCalculationResultConstructor() {
        try {
            // 尝试使用当前类的类加载器
            val className = "com.auto.survey.activity.geosurv.backward.entity.CalculationResult"
            val javaClass = Class.forName(className, true, javaClass.classLoader)

            Log.d("ConstructorSig", "类加载成功: ${javaClass.name}")

            // 尝试直接访问已知的字段
            try {
                val stationField = javaClass.getDeclaredField("station")
                Log.d("ConstructorSig", "找到字段: station (${stationField.type.name})")
            } catch (e: NoSuchFieldException) {
                Log.e("ConstructorSig", "未找到 'station' 字段", e)
            }


            // 打印所有 public 方法的名称
            val publicMethods = javaClass.methods
            Log.d("ConstructorSig", "public 方法数量: ${publicMethods.size}")
            publicMethods.forEachIndexed { index, method ->
                Log.d("ConstructorSig", "public 方法 #$index: ${method.name}")
            }

            // 打印所有声明的方法
            val declaredMethods = javaClass.declaredMethods
            Log.d("ConstructorSig", "声明的方法数量: ${declaredMethods.size}")
            declaredMethods.forEachIndexed { index, method ->
                Log.d("ConstructorSig", "声明的方法 #$index: ${method.name}")
            }

            // 获取所有构造函数（包括非 public）
            val declaredConstructors = javaClass.declaredConstructors
            Log.d("ConstructorSig", "所有构造函数数量=${declaredConstructors.size}")


            // 打印构造函数签名
            for (constructor in declaredConstructors) {
                constructor.isAccessible = true
                val paramTypes = constructor.parameterTypes
                val signature = buildString {
                    append("(")
                    paramTypes.forEach { paramType ->
                        if (paramType.isPrimitive) {
                            when (paramType.name) {
                                "double" -> append("D")
                                "int" -> append("I")
                                else -> append("?")
                            }
                        } else {
                            val className = paramType.name.replace(".", "/")
                            append("L$className;")
                        }
                    }
                    append(")V")
                }
                Log.d("ConstructorSig", "构造函数参数类型：${paramTypes.joinToString { it.name }}")
                Log.d("ConstructorSig", "JNI 签名：$signature")
            }
        } catch (e: ClassNotFoundException) {
            Log.e("ConstructorSig", "类未找到：${e.message}", e)
        } catch (e: NoClassDefFoundError) {
            Log.e("ConstructorSig", "类定义未找到：${e.message}", e)
        } catch (e: Exception) {
            Log.e("ConstructorSig", "反射获取签名失败：${e.message}", e)
        }
    }

    private fun verifyClassStructure() {
        try {
            val className = "com.auto.survey.activity.geosurv.backward.entity.CalculationResult"
            val javaClass = Class.forName(className)

            // 使用 Java 反射
            Log.d("ClassVerify", "Java 反射:")
            Log.d("ClassVerify", "  类名: ${javaClass.name}")
            Log.d("ClassVerify", "  包名: ${javaClass.`package`?.name ?: "unknown"}")
            Log.d("ClassVerify", "  修饰符: ${javaClass.modifiers}")
            Log.d("ClassVerify", "  是否为接口: ${javaClass.isInterface}")
            Log.d("ClassVerify", "  是否为注解: ${javaClass.isAnnotation}")
            Log.d("ClassVerify", "  是否为枚举: ${javaClass.isEnum}")

            // 检查类加载器层级
            var classLoader: ClassLoader? = javaClass.classLoader
            var level = 0
            while (classLoader != null) {
                Log.d("ClassVerify", "  类加载器层级 $level: ${classLoader.javaClass.name}")
                classLoader = classLoader.parent
                level++
            }

            // 尝试获取类的构造函数
            try {
                val constructors = javaClass.declaredConstructors
                Log.d("ClassVerify", "  构造函数数量: ${constructors.size}")
                for (constructor in constructors) {
                    Log.d("ClassVerify", "  构造函数: ${constructor.toGenericString()}")
                }
            } catch (e: Exception) {
                Log.e("ClassVerify", "  获取构造函数失败: ${e.message}")
            }

            // 尝试获取类的字段
            try {
                val fields = javaClass.declaredFields
                Log.d("ClassVerify", "  字段数量: ${fields.size}")
                for (field in fields) {
                    Log.d("ClassVerify", "  字段: ${field.name} (${field.type.name})")
                }
            } catch (e: Exception) {
                Log.e("ClassVerify", "  获取字段失败: ${e.message}")
            }

        } catch (e: Exception) {
            Log.e("ClassVerify", "验证类结构失败: ${e.message}", e)
        }
    }
}